package com.qiguliuxing.dts.job.task;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.google.common.collect.Maps;
import com.qiguliuxing.dts.common.constant.CommConsts;
import com.qiguliuxing.dts.service.base.DtsAccountService;
import com.qiguliuxing.dts.service.merchant.BillStatisService;
import com.qiguliuxing.dts.service.system.SystemConfig;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 商户日统计job
 * @author qiguliuxing
 * @since 1.0.0
 */
@Component
public class MerchantDailyStatisJob  implements SimpleJob {
    private static final Logger logger = getLogger(MerchantDailyStatisJob.class);

    @Autowired
    private DtsAccountService accountService;

    @Autowired
    private BillStatisService billStatisService;

    /**
     * 执行作业.
     *
     * @param shardingContext 分片上下文
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        logger.info(String.format("Thread ID: %s, 作业分片总数: %s, " +
                        "当前分片项: %s.当前参数: %s," +
                        "作业名称: %s.作业自定义参数: %s",
                Thread.currentThread().getId(),
                shardingContext.getShardingTotalCount(),
                shardingContext.getShardingItem(),
                shardingContext.getShardingParameter(),
                shardingContext.getJobName(),
                shardingContext.getJobParameter()
        ));
        // 单商户模式则无需执行逻辑
        if (!SystemConfig.isMultiOrderModel()) {
            logger.warn("警告：单商户模式，商户日统计job无需执行业务逻辑,任务结束!!!");
            return ;
        }

        Map<String, Object> paramsMap = Maps.newHashMapWithExpectedSize(CommConsts.INIT_HASH_MAP_SIZE);
        paramsMap.put("shardingTotalCount", shardingContext.getShardingTotalCount());
        paramsMap.put("shardingItem", shardingContext.getShardingItem());
        List<Integer> brandIds = accountService.findAllBrandUserId(paramsMap);
        logger.info("商户日统计定时任务,共找到  " + brandIds.size() + " 个商户,开始日统计账单...");

        int currCnt = 0;
        for (Integer brandId : brandIds) {
            try {
                billStatisService.mechantDailyStatis(brandId);
                logger.info("商户日统计job进度：共 {} 个，当前执行完 {} 个, 商户id: {}", brandIds.size(), currCnt++, brandId);
            } catch (Exception e) {
                logger.error("商户日统计出错:" + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
